package com.yazi.mxz.gather.main.goods;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yazi.mxz.gather.common.App;
import com.yazi.mxz.gather.entity.enums.ProcessType;
import com.yazi.mxz.gather.entity.repository.ProcessLog;
import com.yazi.mxz.gather.repository.ProcessLogRepository;

public class BsbqsCom extends Thread {
	
	static CloseableHttpAsyncClient httpclient;
	
	static ObjectMapper om;
	
	static {
		httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		
		om = new ObjectMapper();
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	@Override
	public void run() {
		
		ProcessLogRepository logRepository = App.context.getBean(ProcessLogRepository.class);
		ProcessLog log = logRepository.findOne(ProcessType.BSBQS.ordinal());
		if (null == log) {
			log = new ProcessLog();
			log.setId(ProcessType.BSBQS.ordinal());
			log.setCur(1l);
			log.setEnd(Long.MAX_VALUE);
			log.setCount(0);
			logRepository.insert(log);
		}
		
		//log.setCur(1l);
		//log.setCount(0);
		FileWriter fw = null;
		boolean isSocketException = false;
		
		try {
			
			fw = createFile(log.getCount()/5e3);
			
			while (true) {
				
				if (log.getCur() >= log.getEnd()) {
					break;
				}
				
				String str = barcodeInfo(log.getCur());
				
				if (null != str) {
					log.setCount(log.getCount() + 1);
					fw.write(str);
					if (log.getCount()%5e3 == 0) {
						fw.close();
						fw = createFile(log.getCount()/5e3);
					}
				}
				log.setCur(log.getCur() + 1);
				logRepository.save(log);
			
				sleep(200);
				
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
			isSocketException = true;
			
		} catch (Exception e1) {
			e1.printStackTrace();
			
		} finally {     
			try { 
            	
                if(fw != null){  
                	fw.close();     
                }  
                
            } catch (IOException e) {     
                e.printStackTrace();     
            }   
        }  
		
		if (!isSocketException) {
			run();
		}
	}
	
	private FileWriter createFile(double number) throws IOException {
		File file = new File("E:\\项目\\mo_yq5\\barcode\\bsbqs.com\\" + new Double(number).intValue() + ".html");
		if (!file.exists()) {
			file.createNewFile();	
		}
		return new FileWriter(file, true);
	}

	private String barcodeInfo(long goodsId) throws JsonParseException, JsonMappingException,
			IOException, InterruptedException, ExecutionException {
		
		System.out.println( goodsId);
		
		final HttpGet req = new HttpGet("http://www.bsbqs.com/product_edit.php?id=" + goodsId);
		req.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		Future<HttpResponse> future = httpclient.execute(req, null);
		HttpResponse res = future.get();
		
		System.out.println(req.getRequestLine() + "->" + res.getStatusLine());
		
		String body = EntityUtils.toString(res.getEntity(), "utf-8");
		if (body.isEmpty()) {
			System.out.println("无响应内容!");
			return null;
		}
		
		int pidIndex = body.indexOf("name=\"pid\"");
		int readonlyIndex = body.indexOf("readonly=\"readonly\"");
		String partPidHtml = body.substring(pidIndex, readonlyIndex);
		// 条码表单为空时的长度
		if (partPidHtml.length() == 42) {
			System.out.println("商品不存在: " + goodsId);
			return null;
		}
		
		body = body.substring(body.indexOf("<form"), body.indexOf("</form>") + 7);
		// System.out.println(body);
		return body;
	}

}
